package run.halo.hatweb.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import run.halo.app.plugin.ApiVersion;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;

@ApiVersion("hatweb.halo.run/v1alpha1")
@RestController
@RequiredArgsConstructor
@Slf4j
public class UtilController {
    @GetMapping("/util/getRandomMinioPic")
    public Mono<Void> getPerson(ServerWebExchange exchange) {
        try {
            Map<String, String> params = exchange.getRequest().getQueryParams().toSingleValueMap();
            String type = params.get("type");
            String minioUrl = params.get("minioUrl");
            log.info("util getRandomMinioPic type is {} and the url is {}",type,minioUrl);
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> response = restTemplate.getForEntity(minioUrl, String.class);
            String xml = response.getBody();
            XmlMapper xmlMapper = new XmlMapper();
            JsonNode rootNode = xmlMapper.readTree(xml);
            List<String> fileList = new ArrayList<>();
            JsonNode contentsNode = rootNode.path("Contents");
            if (contentsNode.isArray()) {
                for (JsonNode node : contentsNode) {
                    fileList.add(node.path("Key").asText());
                }
            }
            if(CollectionUtils.isEmpty(fileList)){
                return null;
            }
            type = "mobile".equals(type) ? "mobile_" : "PC_";
            log.info(type);
            String finalType = type;
            List<String> res = fileList.stream().filter(v -> v.startsWith(finalType))
                .collect(Collectors.toList());
            Random random = new Random();
            int i = random.nextInt(res.size());
            // 设置 HTTP 头部，告诉浏览器这是一个图片文件
            return Mono.fromRunnable(() -> {
                exchange.getResponse().setStatusCode(HttpStatus
                    .FOUND);
                exchange.getResponse().getHeaders().setLocation(
                    URI.create(minioUrl
                        + "/" + res.get(i)));
            }).then();
        } catch (Exception e) {
            log.error("getRandomMinioPic error info : {}", e.getMessage());
        }
        return null;
    }
}
